from fastapi import FastAPI,Depends
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.middleware.cors import CORSMiddleware
from fastapi.security import HTTPBearer
from fastapi.openapi.utils import get_openapi
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.staticfiles import StaticFiles
from db.database import engine, Base
from utils.response import standard_response
from utils.log_utils import logger
from utils.common import worship
from core.logging_config import setup_logging, log_request
from core.security import token_auth_middleware
from config.cors_config import get_cors_middleware_config
# 路由模块
# from routes import feedback,user_router,test
from routes import registered_routers
from contextlib import asynccontextmanager
from core.Redis import RedisUtil
# from core.scheduler import SchedulerUtil  # 定时任务


# 生命周期管理
@asynccontextmanager
async def lifespan(app: FastAPI):
    # 启动时,创建表（如果不存在）
    Base.metadata.create_all(bind=engine)
    app.state.redis = await RedisUtil.create_redis_pool()
    # init_sys_dict init_sys_config 字典相关暂不需要
    # await RedisUtil.init_sys_dict(app.state.redis)
    # await RedisUtil.init_sys_config(app.state.redis)
    # 定时任务
    # await SchedulerUtil.init_system_scheduler()
    logger.info("启动服务")
    worship()
    yield
    # 关闭时清理资源
    await engine.dispose()
    await RedisUtil.close_redis_pool(app)
    # await SchedulerUtil.close_system_scheduler()

app = FastAPI(
    docs_url=None,
    title="接口API",
    description="基于FastAPI后端服务接口文档",
    root_path="/api",
    # docs_url="/docs",
    openapi_url="/openapi.json",
    # openapi_tags=[
    #     {
    #         "name": "评论",
    #         "description": "API相关操作（中文）",
    #     }
    # ],
    lifespan=lifespan
)
def custom_openapi():
    if app.openapi_schema:
        return app.openapi_schema
    # get_openapi 获取 openapi.json
    openapi_schema = get_openapi(
        title=app.title,
        version="1.0.0",
        description=app.description,
        # root_path=app.root_path,  # 部署的时候生效,不用额外设置
        routes=app.routes,
    )
    # 添加全局 security
    openapi_schema["components"]["securitySchemes"] = {
        "HTTPBearer": {
            "type": "http",
            "scheme": "bearer",
            "bearerFormat": "JWT"
        }
    }
    openapi_schema["security"] = [{"HTTPBearer": []}]
    app.openapi_schema = openapi_schema
    return app.openapi_schema

app.openapi = custom_openapi
setup_logging()

# 中间件必须在路由注册之前添加
# 添加CORS中间件（必须在其他中间件之前添加）
app.add_middleware(
    CORSMiddleware,
    **get_cors_middleware_config()
)

app.add_middleware(
    GZipMiddleware,
    minimum_size=50,  # 只压缩大于 500 字节的响应
    compresslevel=5    # 压缩级别 (1-9, 9 最高)
)
app.middleware("http")(token_auth_middleware)
# app.middleware("http")(log_request)

@app.get("/")
def read_root():
    return {"Hello": "World"}
# 挂载静态文件目录
# app.mount("/static", StaticFiles(directory="static"), name="static")

# 自定义 docs 路由
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
    return get_swagger_ui_html(
        openapi_url=app.openapi_url,
        title="接口API Swagger UI",
        # description="基于FastAPI后端服务接口文档",
        swagger_css_url="https://cdn.bootcdn.net/ajax/libs/swagger-ui/5.11.0/swagger-ui.min.css",
        swagger_js_url="https://cdn.bootcdn.net/ajax/libs/swagger-ui/5.11.0/swagger-ui-bundle.min.js",
        # 静态资源失败
        # swagger_css_url="/static/swagger/swagger-ui.min.css",
        # swagger_js_url="/static/swagger/swagger-ui-bundle.min.js",
    )
# 加载路由（必须在中间件之后注册）
registered_routers(app)

